<template>
  <div>
    <el-container style="height: 100%; border: 1px solid rgb(253, 252, 252)">
      <el-aside width="200px" style="background-color: rgb(255, 255, 255);box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
        <div>
          <el-select v-model="value" placeholder="请选择" size="small" @change="getWell2">
            <el-option v-for="item in data2" :key="item.index" :label="item.company" :value="item.company"></el-option>
          </el-select>
          <el-input size="small" placeholder="关键字查询" v-model="filterText"></el-input>
        </div>
        <el-tree node-key="label" class="filter-tree" :data="data" :props="defaultProps"
          :filter-node-method="filterNode" ref="tree1" :check-on-click-node="true" highlight-current
          @check-change="handleClick" check-strictly></el-tree>
      </el-aside>
      <el-container style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
        <el-header style="text-align: left; font-size: 12px;background-color:#EEF0F6">
          <el-row>
            <el-col :span="4" style="width:80px;margin-right:10px;position: absolute;z-index: 10" >
              <el-upload class="upload-demo" ref="upload" :action="UrlUp"
                :headers="header" :data="{wellName:this.input2}" :on-remove="handleRemove"
                multiple :limit="5" :on-exceed="handleExceed" :before-upload="beforeUpload"  :on-success="TI" >
                <el-button slot="trigger" type="primary" size="small">上传文件</el-button>
                <div slot="tip" class="el-upload__tip"></div>
              </el-upload>
            </el-col>

            <el-col :span="2" style="width:80px;margin-right:10px">
              <el-button type="primary" icon="el-icon-download" @click=" downloadWeekly(filePath)" size="small">下载
              </el-button>
            </el-col>
            <el-col :span="2" style="width:80px;margin-right:10px">
              <el-button type="primary" icon="el-icon-download" @click=" downloadWeekly(filePath)" size="small">下载
              </el-button>
            </el-col>
            <el-col :span="2" style="width:80px;margin-right:10px">
              <el-button type="primary" icon="el-icon-view" @click="previewWeekly(filePath)" size="small">预览</el-button>
            </el-col>
            <el-col :span="2" style="width:80px;margin-right:10px">
              <el-button type="primary" icon="el-icon-view" @click="newWell()" size="small">刷新</el-button>
            </el-col>
            <el-col :span="2" style="width:120px;margin-right:10px">
              <el-input v-model="input4" size="small" placeholder="新文件夹名"></el-input>
            </el-col>
            <el-col :span="2" style="width:80px;margin-right:10px">
              <el-button type="primary" @click="open" size="small">新建文件夹</el-button>
            </el-col>

            <el-col :span="8"></el-col>
          </el-row>
        </el-header>
        <el-main>
          <el-tree default-expand-all node-key="filePath" class="filter-tree" :data="dataT" :props="defaultProps"
            :filter-node-method="filterNode" ref="tree" :check-on-click-node="true" highlight-current
            @check-change="handleClick02" check-strictly></el-tree>
        </el-main>
      </el-container>
      <el-drawer title="手动输入文件上传地址，如：LD10-3-1\固井作业" :visible.sync="drawer" size="30%" :before-close="handleClose">
        <span>
          <el-input v-model="input" placeholder="请输入地址" clearable></el-input>
        </span>
      </el-drawer>
    </el-container>
  </div>

</template>

<script>
  import {
    Tag
  } from "element-ui";
  import pdf from "vue-pdf";
  import Vue from "vue";
  import {
    COOKIE_LIST,
    SERVER_URL
  } from "@/util/constant";
  import Cookie from "js-cookie";
  import {
    downloadPDF,
    getTree,
    getPath,
    upFile,
    getNew
  } from "@/api/module/well";
  import {
    Upload,
    Drawer
  } from "element-ui";
  import {
    getWell,
    getWellDocTree,
    getWellById2,
    getCompany,
    getWellById3,
  } from "@/api/module/wellFind";
  export default {
    components: {
      pdf,
      elUpload: Upload,
      elDrawer: Drawer,
      elTag: Tag,

    },
    watch: {
      filterText(val) {
        this.$refs.tree1.filter(val);
      },
    },
    mounted() {
      this.getCompany();
      this.testURL()
    },
    methods: {
      testURL(){
      this.UrlUp=SERVER_URL+"/dataQuery/upload/"
console.log(this.UrlUp)
      },
        TI(response, file, fileList){
            this.$message.success(
                ` 上传成功`
            )
            this.newWell()
        },
        // TI2(response, file, fileList){
        //     this.$message.error(
        //         ` 上传失败`
        //     )
        // },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //手动刷新
      newWell() {
        this.getWellTree()
        alert('大文件上传如未刷新成功，请稍后再试')
      },
      submitUpload() {
        // console.log(Cookie.get(COOKIE_LIST.AUTHORIZATION))
        this.$refs.upload.submit()
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePreview(file) {
        this.form.fileName = file.name[0]
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        )
      },
      beforeUpload(file, fileList) {

        this.input2 = this.filePathUp.replace(/\\/g, 'xiegang')
        this.input2 = encodeURIComponent(this.input2)
        return this.$confirm(`确定上传到 ${this.filePathUp}？(如地址错误请双击后重试)`)
      },
      // 预览
      previewWeekly(wellName) {
        // 调用子组件的预览方法
        // 完整的地址应该是发布到服务器的地址，不应该是localhost:8080这样的
        // Vue.prototype.ApiUrl 用来读取服务器地址 比如:
        // http://192.168.8.152:8080/MixShowView-Web/reports/preview/1
        wellName = this.filePath;
        console.log(this.filePath)
        var suffix_wellName = wellName.split(".")[wellName.split(".").length - 1];
        if (
          suffix_wellName == "pdf" ||
          suffix_wellName == "png" ||
          suffix_wellName == "jpg" ||
          suffix_wellName == "PNG" ||
          suffix_wellName == "bmp" ||
          suffix_wellName == "tif" ||
          suffix_wellName == "JPEG" ||
          suffix_wellName == "gif"
        ) {
          this.previewPDF(
            SERVER_URL + "/dataQuery/preview/" + wellName
          );
        } else {
          alert("该文件格式不支持预览");
        }
      },
      // 封装预览pdf
      previewPDF(url) {
        this.src = pdf.createLoadingTask(url);
        window.open(url);
      },
      // 下载
      downloadWeekly(fileName) {
        this.test = fileName;
        downloadPDF(this.test)
          .then((res) => {
            // 调用下载方法，把后端传过来的流传给fileDownload方法
            this.fileDownload(res.data, fileName);
            console.log(res);
            console.log(res.config.url);
            this.src0 = res.config.url;
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
        // 调用下载方法
        // this.$refs.pdf.downloadPDF(Vue.prototype.ApiUrl + '/reports/download/' + fileName)
      },
      // 封装的下载方法
      fileDownload: function (data, fileName) {
        let blob = new Blob([data], {
          // type类型后端返回来的数据中会有，根据自己实际进行修改
          type: "application/octet-stream",
        });
        let filename = this.d;
        if (typeof window.navigator.msSaveBlob !== "undefined") {
          window.navigator.msSaveBlob(blob, filename);
        } else {
          var blobURL = window.URL.createObjectURL(blob);
          // 创建隐藏<a>标签进行下载
          var tempLink = document.createElement("a");
          tempLink.style.display = "none";
          tempLink.href = blobURL;
          tempLink.setAttribute("download", filename);
          if (typeof tempLink.download === "undefined") {
            tempLink.setAttribute("target", "_blank");
          }
          document.body.appendChild(tempLink);
          tempLink.click();
          document.body.removeChild(tempLink);
          window.URL.revokeObjectURL(blobURL);
        }
      },
      //获得文件名以及路径
      handleClick02(data, checked, node) {
        if (checked) {
          this.$refs.tree.setCheckedNodes([data]);
          if (typeof data.children === "undefined") {
            this.getDWell1();
          } else {
            let filePath01 = data.fileParent.split("\\");
            var filePath02 = ''
            for (let index = 0; index < filePath01.length; index++) {
              filePath02 = filePath02 + filePath01[index] + '\\'
            }
            filePath02 = filePath02.substring(0, filePath02.length - 1);
            console.log(filePath01)
            console.log(filePath02)
            this.filePathUp = filePath02
          }
        }
      },
      //获得文件信息
      getDWell1() {
        this.b = this.$refs.tree.getCheckedKeys();
        var c = this.b[0];
        this.d = c.split("\\")[c.split("\\").length - 1];

        this.b.forEach((item) => {
          if (item !== "") {
            this.filePath = item.replace(/\\\\/g, "\\");
            this.filePath = this.filePath.replace(/\\/g, "xiegang");
            this.filePath = encodeURIComponent(this.filePath);
            this.a = this.filePath;
          }
        });
        // this.b.filter(item => item !== "")
        // console.log(this.b.filter(item => item !== ""))
        // let a = this.b.filter(item => item !== "")[0]
        // a = a.replace(/\\\\/g, '\\')
        //      a = a.replace(/\\/g, 'xiegang')
        //      a=encodeURIComponent(a)
        //      this.a = a
      },
      //获得文件树
      getWellTree() {
        this.WellName = JSON.parse(JSON.stringify(this.WellName));
        this.input2 = this.WellName
        getTree(this.WellName)
          .then((res) => {
            this.dataT = res.data.data;
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      },
      ////点击叶子节点触发方法
      handleClick(data, checked, node) {
        if (checked) {
          this.$refs.tree.setCheckedNodes([data]);
          if (typeof data.children[0] == "undefined") {
            this.WellName = data.label
              this.filePathUp=data.label
            this.getWellTree();
          }
        }
      },
      //获得公司
      getCompany() {
        getCompany()
          .then((res) => {
            //   this.data = res.data.data
            this.data2 = res.data.data2;
            this.value = res.data.data3;
            this.getWell2();
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      },
      //新建文件夹
      open() {
        this.input5 = this.filePathUp + '\\' + this.input4
        console.log(this.input5)
        this.input5 = this.input5.replace(/\\/g, 'xiegang')
        this.input5 = encodeURIComponent(this.input5)
          getNew(this.input5)
            .then((res) => {
           })
            .catch((err) => {
              this.$message.error(err.message);
          });

      },
      //获得树
      getWell2() {
        this.nCompany = encodeURIComponent(this.value);
        getWellById3(this.nCompany)
          .then((res) => {
            this.data = res.data.data;
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      },
      //  getTress() {
      //    getWellDocTree().then((res) => {
      //     console.log(res)
      //    }).catch((err) => {
      //     this.$message.error(err.message)
      //    })
      //  },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      //点击叶子节点触发方法
    },
    data() {
      return {
        UrlUp:'',
        dialogVisible: false,
        drawer: false,
        fileList: [],
        filePath: "",
        filePathUp: "",
        a: "",
        b: "",
        c: "",
        d: "",
        value: "",
        nCompany: [],
        WellName: [],
        data: [],
        data2: [],
        data3: [],
        input: '',
        input2: [],
        input3: [],
        input4: [],
        input5: [],
        dataT: [],
        filterText: "",
        defaultProps: {
          children: "children",
          label: "label",
        },
        // 文件上传设定token
        header: {
          Authorization: Cookie.get(COOKIE_LIST.AUTHORIZATION),
        },
      };
    },
  };

</script>
<style scoped>
  .el-header {
    background-color: rgb(252, 252, 252);
    color: rgb(244, 245, 240);
    line-height: 60px;
  }

  .el-aside {
    color: rgb(252, 252, 252);
  }

  .abc {
    color: rgb(244, 245, 240);
    height: 19px;
  }

</style>
